package fi.foyt.cs.persistence.dao.task;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import fi.foyt.cs.persistence.dao.GenericDAO;
import fi.foyt.cs.persistence.domainmodel.task.TaskRequirementItem;

public class TaskRequirementItemDAO extends GenericDAO<TaskRequirementItem> {

  public TaskRequirementItem create(Long taskRequirementsId, Long itemId, Integer count) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      TaskRequirementItem taskRequirementItem = new TaskRequirementItem();
      taskRequirementItem.setCount(count);
      taskRequirementItem.setTaskRequirementsId(taskRequirementsId);
      taskRequirementItem.setItemId(itemId);
      entityManager.persist(taskRequirementItem);
      entityManager.getTransaction().commit();
      return taskRequirementItem;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }

  @SuppressWarnings("unchecked")
  public List<TaskRequirementItem> listByTaskRequirementsId(Long taskRequirementsId) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from TaskRequirementItem o where taskRequirementsId = :taskRequirementsId");
    query.setParameter("taskRequirementsId", taskRequirementsId);
    return query.getResultList();
  }
  
  public TaskRequirementItem updateCount(TaskRequirementItem taskRequirementItem, Integer count) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      taskRequirementItem.setCount(count);
      taskRequirementItem = entityManager.merge(taskRequirementItem);
      entityManager.getTransaction().commit();

      return taskRequirementItem;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
  
  public TaskRequirementItem updateItemId(TaskRequirementItem taskRequirementItem, Long itemId) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      taskRequirementItem.setItemId(itemId);
      taskRequirementItem = entityManager.merge(taskRequirementItem);
      entityManager.getTransaction().commit();

      return taskRequirementItem;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
}
